import send from '../config/MailConfig'
import bcrypt from 'bcrypt'
import moment from 'moment'
import jsonwebtoken from 'jsonwebtoken'
import config from '../config/index'
import { checkCode } from '../common/utils'
import User from '../model/user'

class LoginController {
  constructor() {}

  async forget(ctx) {
    const { body } = ctx.request
    try {
      // body.username -> database -> email
      let result = await send({
        code: '1234',
        expire: moment()
          .add(30, 'minutes')
          .format('YYYY-MM-DD HH:mm:ss'),
        email: body.username,
        user: 'Brian',
      })
      ctx.body = {
        code: 200,
        data: result,
        msg: '邮件发送成功',
      }
    } catch (e) {
      console.log(e)
    }
  }

  async login(ctx) {
    // 接受用户数据
    // 验证图片验证码时效性和正确性
    // 验证用户账户密码是否正确
    // 返回token
    const { body } = ctx.request
    const sid = body.sid
    const code = body.code
    const result = await checkCode(sid, code) 

    // 判断验证码
    if(result) {
      // 验证用户账号密码是否正确
      let checkUserPasswd = false
      let user = await User.findOne({
        username: body.username
      })
      if (user === null) {
        ctx.body = {
          code: 404,
          msg: '用户名或者密码错误'
        }
        return
      }
      if(await bcrypt.compare(body.password,user.password)) {
        checkUserPasswd = true
      }

      // 验证账号密码是否正确
      if(checkUserPasswd) {
        const userObj = user.toJSON()
        const arr = ['password', 'username']
        arr.map((item) => {
          delete userObj[item]
        })

        let token = jsonwebtoken.sign({
          _id: 'brian'
        },config.JWT_SECRET, {
          expiresIn: '1d'
        })

        // // 加入isSign属性
        // const signRecord = await SignRecord.findByUid(userObj._id)

        // if (signRecord !== null) {
        //   if (moment(signRecord.created).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')) {
        //     userObj.isSign = true
        //   } else {
        //     userObj.isSign = false
        //   }
        //   userObj.lastSign = signRecord.created
        // } else {
        //   // 用户无签到记录
        //   userObj.isSign = false
        // }
        // 返回token
        ctx.body = {
          code: 200,
          token: token
        }
      } else {
        // 帐号或密码错误
        ctx.body = {
          code: 404,
          msg: '帐号或密码错误！'
        }
      }
      
    } else {
      // 如果验证码错误
      ctx.body = {
        code: 401,
        msg: '验证码不正确！'
      }
    }

    
  }

  async reg(ctx) {
    const { body } = ctx.request
    const sid = body.sid
    const code = body.code
    const result = await checkCode(sid, code)
    let check = true
    let msg = {}

    if(result) {
      const user1 = await User.findOne({
        username: body.username
      })

      if (user1 !== null && typeof user1.username !== 'undefined') {
        msg.username = ['此邮箱已注册，可通过邮箱找回密码']
        check = false
      }

      const user2 = await User.findOne({
        name: body.name
      })

      if (user2 !== null && typeof user2.name !== 'undefined') {
        msg.name = ['此昵称已存在，请使用其他昵称']
        check = false
      }

      if(check) {
        body.password = await bcrypt.hash(body.password, 5)
        let user = new User({
          username: body.username,
          name: body.name,
          password: body.password,
          created: moment().format('YYYY-MM-DD HH:mm:ss')
        })
        let res = await user.save()
        ctx.body = {
          code: 200,
          data: res,
          msg: '注册成功！'
        }
        return
      }
    } else {
      msg.code = ['验证码已失效，请重新获取']
    }
    ctx.body = {
      code: 500,
      msg: msg
    }
  }

  // 密码重置
  async reset (ctx) {
    const { body } = ctx.request
    const sid = body.sid
    const code = body.code
    let msg = {}
    // 验证图片验证码的时效性、正确性
    const result = await checkCode(sid, code)
    if (!body.key) {
      ctx.body = {
        code: 500,
        msg: '请求参数异常，请重新获取链接'
      }
      return
    }
    if (!result) {
      msg.code = ['验证码已经失效，请重新获取！']
      ctx.body = {
        code: 500,
        msg: msg
      }
      return
    }
    const token = await getValue(body.key)
    if (token) {
      const obj = getJWTPayload('Bearer ' + token)
      body.password = await bcrypt.hash(body.password, 5)
      await User.updateOne(
        { _id: obj._id },
        {
          password: body.password
        }
      )
      ctx.body = {
        code: 200,
        msg: '更新用户密码成功！'
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '链接已经失效'
      }
    }
  }
}

export default new LoginController()
